/*******************************************************************************
 * @note Copyright (C) 2011-2022， Shanghai Panchip Microelectronics Co., Ltd. 
 * @SPDX-License-Identifier: Apache-2.0
 * @history - V0.1, 2022-09-28
*******************************************************************************/
#include "spi.h"
#include "hardware.h"
#include "timer3.h"
#include <stdio.h>
#include "service_pt.h"
#include "bt.h"
#include "trng.h"
#include "dmac.h"


uint8_t uart_rx_buf[RX_FIFO_SIZE];
Fifo_t uart_rx_fifo = {0, 0,  RX_FIFO_SIZE,  0, (uint8_t *)uart_rx_buf};

uint8_t uart_tx_buf[TX_FIFO_SIZE];
Fifo_t uart_tx_fifo = {0, 0,  TX_FIFO_SIZE,  0, (uint8_t *)uart_tx_buf};

uint32_t uart_baudrate = 115200;    //uart baudrate

/*
 * After the node receives the lastbyte of package, 
 * it will wait for a short period (2~3 bytes). 
 * uart_packing_interval is the short period.
 * * □□□<package>□□□<package>□□□
 */
uint32_t uart_packing_interval = 5;
uint32_t uart_idle_timer_cnt = 59536;

/* aux pin mode
 * aux_mode=0
 *   AUX=0: fifo is empty
 *   AUX=1: fifo is not empty
 *  aux_mode=1
 *   AUX=0: fifo is not full
 *   AUX=1: fifo is full
 */
int aux_mode = AUX_MODE_EMPTY;

bool uart_rx_busy_flag = FALSE;
bool uart_tx_busy_flag = FALSE;

#ifdef DDL_UART_DMA_YES
volatile bool uart_dmac_tx_flag = FALSE;
#endif

volatile aux_level_t aux_level = {LEVEL_INACTIVE, LEVEL_INACTIVE, LEVEL_INACTIVE, LEVEL_INACTIVE};

extern void nm_set_io_op(void);
extern void pt_uart_set_rx_evt(void);
extern void net_uart_set_evt(void);
extern void pt_io_set_evt(void);

bool aux_level_set(aux_type_t type, bool level)
{
    switch ( type )
    {
        case AUX_INIT :
            aux_level.init = level;
            break;
        case AUX_JOIN :
            aux_level.join = level;
            break;
        case AUX_DATA :
            aux_level.data = level;
            break;
        case AUX_FIFO :
            aux_level.fifo = level;
            break;
        case AUX_SLEEP :
            aux_level.sleep = level;
            break;
        case AUX_ERROR :
            aux_level.error = level;
            break;
        default:
            break;
    }

    if ( level == LEVEL_ACTIVE )
    {
        GPIO_AUX_LEVEL_SET_H;
    }
    else
    {
        if ( aux_level.init == LEVEL_INACTIVE
             && aux_level.join == LEVEL_INACTIVE
             && aux_level.data == LEVEL_INACTIVE
             && aux_level.fifo == LEVEL_INACTIVE
             && aux_level.sleep == LEVEL_INACTIVE
             && aux_level.error == LEVEL_INACTIVE)
        {
            GPIO_AUX_LEVEL_SET_L;
        }
        else
        {
            GPIO_AUX_LEVEL_SET_H;
        }
    }
    
    return GPIO_AUX_LEVEL_GET();
}

void hw_clk_div_init(void)
{
    //时钟分频设置
    Sysctrl_SetHCLKDiv(SysctrlHclkDiv1);
    Sysctrl_SetPCLKDiv(SysctrlPclkDiv1);
}

void app_clk_init(void)
{
    stc_sysctrl_clk_cfg_t stcCfg;
    
    ///< 开启FLASH外设时钟
    Sysctrl_SetPeripheralGate(SysctrlPeripheralFlash, TRUE);
    
    ///< 因要使用的时钟源HCLK小于24M：此处设置FLASH 读等待周期为0 cycle(默认值也为0 cycle)
    Flash_WaitCycle(FlashWaitCycle0);
    
    ///< 时钟初始化前，优先设置要使用的时钟源：此处设置RCH为4MHz
    Sysctrl_SetRCHTrim(SysctrlRchFreq24MHz);
    
    ///< 选择内部RCH作为HCLK时钟源;
    stcCfg.enClkSrc    = SysctrlClkRCH;
    ///< HCLK SYSCLK/1
    stcCfg.enHClkDiv   = SysctrlHclkDiv1;
    ///< PCLK 为HCLK/1
    stcCfg.enPClkDiv   = SysctrlPclkDiv1;
    ///< 系统时钟初始化
    Sysctrl_ClkInit(&stcCfg);
}

uint8_t hw_pll_init(void)
{
	app_clk_init();
    hw_clk_div_init();
    
    return TRUE;
}

void Rtc_IRQHandler(void)
{
    if(Rtc_GetPridItStatus() == TRUE)
    {
        Rtc_ClearPrdfItStatus();
    }
}

void hw_rtc_cfg(int on, float second)
{
    if ( on )
    {
        stc_rtc_initstruct_t RtcInitStruct;
        
        Sysctrl_ClkSourceEnable(SysctrlClkRCL, TRUE);
        Sysctrl_SetPeripheralGate(SysctrlPeripheralRtc, TRUE);
        
        DDL_ZERO_STRUCT(RtcInitStruct);
        
        RtcInitStruct.rtcClksrc = RtcClkRcl;
        RtcInitStruct.rtcPrdsel.rtcPrdsel = RtcPrdx; 
        RtcInitStruct.rtcPrdsel.rtcPrdx = (uint8_t)(second*2)-1; //time step=0.5s
        Rtc_Init(&RtcInitStruct);
 
        Rtc_ClearPrdfItStatus();

        Rtc_AlmIeCmd(TRUE);                                     //IRQ               
        Rtc_Cmd(TRUE);                                          //Enable
        Rtc_StartWait();                                        //Wait
        EnableNvic(RTC_IRQn, IrqLevel3, TRUE); 
    }
    else
    {
        Rtc_DeInit();
        EnableNvic(RTC_IRQn, IrqLevel3, FALSE);
        Rtc_ClearPrdfItStatus();
    }
}

void hw_gpio_cfg(void)
{
    /* PB3->SETA
       PB4->SETB
       PB5->AUX  */
    stc_gpio_cfg_t stcGpioCfg;

    Sysctrl_SetPeripheralGate(SysctrlPeripheralGpio, TRUE);

    stcGpioCfg.enDrv = GpioDrvH;
    stcGpioCfg.enDir = GpioDirOut;
    stcGpioCfg.enPu  = GpioPuDisable;
    stcGpioCfg.enPd  = GpioPdDisable;
    stcGpioCfg.enOD  = GpioOdDisable;
    stcGpioCfg.enCtrlMode = GpioAHB;
    Gpio_Init(GPIO_PORT_AUX, GPIO_PIN_AUX, &stcGpioCfg);   //AUX
    
    /* AUX level is high, inditate node is initing */
    aux_level_set(AUX_INIT, LEVEL_ACTIVE);
#ifdef USBDONGLE
	stcGpioCfg.enDir  = GpioDirOut;
	Gpio_Init(GpioPortA, GpioPin8, &stcGpioCfg);	//18B20
	Gpio_WriteOutputIO(GpioPortA, GpioPin8, FALSE); 
#endif
    stcGpioCfg.enDir = GpioDirIn;
    stcGpioCfg.enDrv = GpioDrvL;
    stcGpioCfg.enPu  = GpioPuEnable;
    stcGpioCfg.enPd  = GpioPdDisable;
    stcGpioCfg.enOD  = GpioOdDisable;
    stcGpioCfg.enCtrlMode = GpioAHB;

    Gpio_Init(GPIO_PORT_SETA, GPIO_PIN_SETA, &stcGpioCfg); //SETA
    Gpio_Init(GPIO_PORT_SETB, GPIO_PIN_SETB, &stcGpioCfg); //SETB

    stcGpioCfg.enDir = GpioDirIn;
    stcGpioCfg.enDrv = GpioDrvL;
    stcGpioCfg.enPu = GpioPuDisable;
    stcGpioCfg.enPd = GpioPdEnable;
    stcGpioCfg.enOD = GpioOdDisable;
    stcGpioCfg.enCtrlMode = GpioAHB;
    Gpio_Init(GPIO_PORT_IRQ, GPIO_PIN_IRQ, &stcGpioCfg);//pan3028 irq
    Gpio_Init(GPIO_PORT_CAD, GPIO_PIN_CAD, &stcGpioCfg);//cad check
    
    Gpio_EnableIrq(GPIO_PORT_IRQ, GPIO_PIN_IRQ, GpioIrqRising);
    Gpio_EnableIrq(GPIO_PORT_CAD, GPIO_PIN_CAD, GpioIrqRising);
    
    Gpio_EnableIrq(GPIO_PORT_SETA, GPIO_PIN_SETA, GpioIrqRising);
    Gpio_EnableIrq(GPIO_PORT_SETB, GPIO_PIN_SETB, GpioIrqRising);
    
    EnableNvic(PORTA_IRQn, IrqLevel3, TRUE);
    EnableNvic(PORTB_IRQn, IrqLevel3, TRUE);
}

/**
 ******************************************************************************
 ** \brief  初始化外部GPIO引脚
 **
 ** \return 无
 ******************************************************************************/
void hw_spi_gpio_init(void)
{
    stc_gpio_cfg_t stcGpioCfg;

    //SPI0引脚配置:主机
    stcGpioCfg.enDrv = GpioDrvH;
    stcGpioCfg.enDir = GpioDirOut;
    stcGpioCfg.enPu  = GpioPuDisable;
    stcGpioCfg.enPd  = GpioPdDisable;
    stcGpioCfg.enOD  = GpioOdDisable;
    stcGpioCfg.enCtrlMode = GpioAHB;

    Spi_SetCS(M0P_SPI0, TRUE);
    Gpio_Init(GpioPortA, GpioPin4, &stcGpioCfg);
    Gpio_SetAfMode(GpioPortA, GpioPin4, GpioAf1);  //配置引脚PA04作为SPI0_CS
    Spi_SetCS(M0P_SPI0, TRUE);

    Gpio_Init(GpioPortA, GpioPin7, &stcGpioCfg);
    Gpio_SetAfMode(GpioPortA, GpioPin7, GpioAf1);  //配置引脚PA7作为SPI0_MOSI
    
    Gpio_Init(GpioPortA, GpioPin5, &stcGpioCfg);
    Gpio_SetAfMode(GpioPortA, GpioPin5, GpioAf1);  //配置引脚PA05作为SPI0_SCK

    stcGpioCfg.enDir = GpioDirIn;
    Gpio_Init(GpioPortA, GpioPin6, &stcGpioCfg);
    Gpio_SetAfMode(GpioPortA, GpioPin6, GpioAf1);  //配置引脚PA06作为SPI0_MISO
}

/**
 ******************************************************************************
 ** \brief  初始化SPI
 **
 ** \return 无
 ******************************************************************************/
void hw_spi_cfg(void)
{
    stc_spi_cfg_t SpiInitStruct;

    Sysctrl_SetPeripheralGate(SysctrlPeripheralSpi0,TRUE);

    //SPI0模块配置：主机
    SpiInitStruct.enSpiMode = SpiMskMaster;     //配置位主机模式
    SpiInitStruct.enPclkDiv = SpiClkMskDiv16;   //波特率：fsys/128
    SpiInitStruct.enCPHA    = SpiMskCphafirst;  //第一边沿采样
    SpiInitStruct.enCPOL    = SpiMskcpollow;    //极性为低
    Spi_Init(M0P_SPI0, &SpiInitStruct);
    Spi_ClearStatus(M0P_SPI0);

    hw_spi_gpio_init();
}

///< PortA中断服务函数
void PortA_IRQHandler(void)
{
    if(Gpio_GetIrqStatus(GPIO_PORT_IRQ, STK_IRQ_PIN))//A2->3028IRQ
    {
        rf_irq_handler();  
        Gpio_ClearIrq(GPIO_PORT_IRQ, STK_IRQ_PIN);
    }
    
    if(Gpio_GetIrqStatus(GPIO_PORT_CAD, GPIO_PIN_CAD))//A15->CAD
    {
        Gpio_ClearIrq(GPIO_PORT_CAD, GPIO_PIN_CAD);
    }
}

///< PortB中断服务函数
void PortB_IRQHandler(void)
{
    if(Gpio_GetIrqStatus(GPIO_PORT_SETA, GPIO_PIN_SETA))
    {
        nm_set_io_op();
        Gpio_ClearIrq(GPIO_PORT_SETA, GPIO_PIN_SETA);
    }
    
    if ( Gpio_GetIrqStatus(GPIO_PORT_SETB, GPIO_PIN_SETB) )
    {
        Gpio_ClearIrq(GPIO_PORT_SETB, GPIO_PIN_SETB);
    }
    
    if(Gpio_GetIrqStatus(GPIO_PORT_IRQ, GPIO_PIN_IRQ))//PB0->RF_IRQ
    {
        rf_irq_handler();  
        Gpio_ClearIrq(GPIO_PORT_IRQ, GPIO_PIN_IRQ);
    }
    
    if(Gpio_GetIrqStatus(GPIO_PORT_CAD, GPIO_PIN_CAD))//PB1->RF_CAD
    {
		extern chirplan_proc_t chirplan_proc;
		chirplan_proc.cad_tx_timeout_flag |= MAC_EVT_TX_CAD_ACTIVE;
		stimer_stop(&chirplan_proc.stimer_chirplan_cad_event);
        Gpio_ClearIrq(GPIO_PORT_CAD, GPIO_PIN_CAD);
    }
}

///< PortD中断服务函数
void PortD_IRQHandler(void)
{
    if(Gpio_GetIrqStatus(GpioPortD, GpioPin4))
    {
        Gpio_ClearIrq(GpioPortD, GpioPin4);
    }
}

void hw_lp_enter_gpio_cfg(void)
{
    stc_gpio_cfg_t stcGpioCfg;
    
    Gpio_DisableIrq(GPIO_PORT_IRQ, GPIO_PIN_IRQ, GpioIrqRising);
    Gpio_DisableIrq(GPIO_PORT_CAD, GPIO_PIN_CAD, GpioIrqRising);

    if ( GPIO_SETA_LEVEL_GET() )
    {
        Gpio_EnableIrq(GPIO_PORT_SETA, GPIO_PIN_SETA, GpioIrqFalling);
    }
    else
    {
        Gpio_EnableIrq(GPIO_PORT_SETA, GPIO_PIN_SETA, GpioIrqRising);
    }
    
    if ( GPIO_SETB_LEVEL_GET() )
    {
        Gpio_EnableIrq(GPIO_PORT_SETB, GPIO_PIN_SETB, GpioIrqFalling);
    }
    else
    {
        Gpio_EnableIrq(GPIO_PORT_SETB, GPIO_PIN_SETB, GpioIrqRising);
    }

    stcGpioCfg.enDir = GpioDirIn;
    stcGpioCfg.enPu  = GpioPuDisable;
    stcGpioCfg.enDrv = GpioDrvL;

    /* spi tx rx gpio config */
    stcGpioCfg.enPu  = GpioPuDisable;
    stcGpioCfg.enPd  = GpioPdDisable;
    Gpio_Init(GpioPortA, GpioPin5, &stcGpioCfg);
    Gpio_Init(GpioPortA, GpioPin6, &stcGpioCfg);
    Gpio_Init(GpioPortA, GpioPin7, &stcGpioCfg);

    /* rf irq/cad gpio config */
    stcGpioCfg.enPu  = GpioPuDisable;
    stcGpioCfg.enPd  = GpioPdDisable;
    Gpio_Init(GPIO_PORT_IRQ, GPIO_PIN_IRQ, &stcGpioCfg);
    Gpio_Init(GPIO_PORT_CAD, GPIO_PIN_CAD, &stcGpioCfg);

    Gpio_Init(GpioPortB, GpioPin3, &stcGpioCfg);
	Gpio_Init(GpioPortB, GpioPin4, &stcGpioCfg);
	Gpio_Init(GpioPortB, GpioPin5, &stcGpioCfg);
}

void hw_lp_exit_gpio_cfg(void)
{
    stc_gpio_cfg_t stcGpioCfg;
    
    stcGpioCfg.enDir = GpioDirIn;
    stcGpioCfg.enDrv = GpioDrvL;
    stcGpioCfg.enPu = GpioPuDisable;
    stcGpioCfg.enPd = GpioPdEnable;
    stcGpioCfg.enOD = GpioOdDisable;
    stcGpioCfg.enCtrlMode = GpioAHB;
    Gpio_Init(GPIO_PORT_IRQ, GPIO_PIN_IRQ, &stcGpioCfg);//pan3028 irq
    Gpio_EnableIrq(GPIO_PORT_IRQ, GPIO_PIN_IRQ, GpioIrqRising);
    
    Gpio_Init(GPIO_PORT_CAD, GPIO_PIN_CAD, &stcGpioCfg);//cad check
    Gpio_EnableIrq(GPIO_PORT_CAD, GPIO_PIN_CAD, GpioIrqRising);
    
    EnableNvic(PORTA_IRQn, IrqLevel3, TRUE);
    EnableNvic(PORTB_IRQn, IrqLevel3, TRUE);

    stcGpioCfg.enPu = GpioPuEnable;
    stcGpioCfg.enPd = GpioPdDisable;

    Gpio_Init(GpioPortB, GpioPin3, &stcGpioCfg);
	Gpio_Init(GpioPortB, GpioPin4, &stcGpioCfg);

    hw_spi_gpio_init();
}


//UART1中断函数
void Uart0_IRQHandler(void)
{
    static uint8_t u8RxData;

    if(Uart_GetStatus(M0P_UART0, UartRC))         //UART0 rx irq
    {
        u8RxData = Uart_ReceiveData(M0P_UART0);   //get data
        Uart_ClrStatus(M0P_UART0, UartRC);        //clear rx flag

        /* uart tx rx conflict */
        if ( uart_tx_busy_flag )
        {
            uart_rx_busy_flag = FALSE;
            uart_rx_fifo_flush();
			Bt_M0_Stop(TIM1);
			Bt_ClearIntFlag(TIM1,BtUevIrq);
            return;
        }
        
        /* indicate that package is receiving */
        uart_rx_busy_flag = TRUE;
        
        if(!fifo_is_full(&uart_rx_fifo))
        {
            fifo_push(&uart_rx_fifo, u8RxData);
            /* if fifo is not empty,set aux high */
            if ( aux_mode == AUX_MODE_EMPTY )
            {
                aux_level_set(AUX_FIFO, LEVEL_ACTIVE);
            }
        }
        else
        {
            uart_rx_busy_flag = FALSE;
            
            /* set uart recv evt */
            pt_uart_set_rx_evt();
            net_uart_set_evt();

            /* if fifo is full,set aux high */
            if ( aux_mode == AUX_MODE_FULL )
            {
                aux_level_set(AUX_FIFO, LEVEL_ACTIVE);
            }
        }
        
        hw_timer1_restart();
    }
    else if(Uart_GetStatus(M0P_UART0, UartTC)) 
    {
        Uart_ClrStatus(M0P_UART0, UartTC);
    }
    else if(Uart_GetStatus(M0P_UART0, UartFE)) 
    {
        Uart_ClrStatus(M0P_UART0, UartFE);
    }
    else if(Uart_GetStatus(M0P_UART0, UartTxe)) 
    {
        Uart_ClrStatus(M0P_UART0, UartTxe);
    }
    else if(Uart_GetStatus(M0P_UART0, UartPE)) 
    {
        Uart_ClrStatus(M0P_UART0, UartPE);
    }
    else if(Uart_GetStatus(M0P_UART0, UartCtsIf)) 
    {
        Uart_ClrStatus(M0P_UART0, UartCtsIf);
    }
    else if(Uart_GetStatus(M0P_UART0, UartCts)) 
    {
        Uart_ClrStatus(M0P_UART0, UartCts);
    }
}

//串口引脚配置
void hw_uart_gpio_init(void)
{
    stc_gpio_cfg_t stcGpioCfg;
    DDL_ZERO_STRUCT(stcGpioCfg);
    Sysctrl_SetPeripheralGate(SysctrlPeripheralGpio,TRUE); //使能GPIO模块时钟
    
    stcGpioCfg.enCtrlMode = GpioAHB;
    stcGpioCfg.enDrv = GpioDrvL;
    stcGpioCfg.enOD  = GpioOdDisable;
    stcGpioCfg.enPd  = GpioPdDisable;
    
    stcGpioCfg.enDir = GpioDirOut;
    stcGpioCfg.enPu  = GpioPuDisable;
    Gpio_Init(GpioPortA, GpioPin9, &stcGpioCfg);
    Gpio_SetAfMode(GpioPortA, GpioPin9, GpioAf1); //配置PA09 端口为URART0_TX

    stcGpioCfg.enDir = GpioDirIn;
    stcGpioCfg.enPu  = GpioPuEnable;
    Gpio_Init(GpioPortA, GpioPin10, &stcGpioCfg);
    Gpio_SetAfMode(GpioPortA, GpioPin10, GpioAf1); //配置PA10 端口为URART0_RX
}

//串口配置
void hw_uart_cfg(void)
{
    stc_uart_cfg_t stcCfg;
    DDL_ZERO_STRUCT(stcCfg);
    Sysctrl_SetPeripheralGate(SysctrlPeripheralUart0, TRUE);///<使能uart0模块时钟

	extern node_config_t node_config;
    stcCfg.enRunMode        = UartMskMode1;          ///<模式1
	if(node_config.uart_stopbit == 2)
	{
		stcCfg.enStopBit        = UartMsk2bit;
	}else{
		stcCfg.enStopBit        = UartMsk1bit;           ///<1bit停止位
	}
   
	if(node_config.uart_parity == 1)
	{
		stcCfg.enMmdorCk        = UartMskOdd;
	}else if(node_config.uart_parity == 2)
	{
		stcCfg.enMmdorCk        = UartMskEven;
	}else{
		stcCfg.enMmdorCk        = UartMskDataOrAddr;
	}

    stcCfg.stcBaud.u32Baud  = node_config.uart_baudrate;         ///<波特率9600
    stcCfg.stcBaud.enClkDiv = UartMsk8Or16Div;       ///<通道采样分频配置
    stcCfg.stcBaud.u32Pclk  = Sysctrl_GetPClkFreq(); ///<获得外设时钟（PCLK）频率值
    Uart_Init(M0P_UART0, &stcCfg);                   ///<串口初始化
	
    ///<UART中断使能
    Uart_ClrStatus(M0P_UART0,UartRC);                ///<清接收请求
    Uart_ClrStatus(M0P_UART0,UartTC);                ///<清接收请求
    Uart_EnableIrq(M0P_UART0,UartRxIrq);             ///<使能串口接收中断

    EnableNvic(UART0_IRQn, IrqLevel0, TRUE);         ///<系统中断使能

}

int uart_fifo_read(u8 *buf, int bufLen)
{
    int len = 0;

    for(int i = 0; i < bufLen; i++)
    {
        if(!fifo_is_empty(&uart_rx_fifo))
        {
            buf[i] = fifo_pop(&uart_rx_fifo);
            len++;
        }
        else
        {
            break;
        }
    }

    return len;
}

void uart_rx_fifo_flush(void)
{
    fifo_flush(&uart_rx_fifo);
}

/*******************************************************************************
 * TIM0中断服务函数
 ******************************************************************************/
void Tim0_IRQHandler(void)
{
    static uint8_t i;
    
    //Timer0 模式0 溢出中断
    if(TRUE == Bt_GetIntFlag(TIM0, BtUevIrq))
    {
        Bt_ClearIntFlag(TIM0,BtUevIrq); //中断标志清零
    }
}

//Timer0配置初始化
void hw_timer0_cfg(void)
{
    uint16_t u16ArrValue;
    uint16_t u16CntValue;
    stc_bt_mode0_cfg_t stcBtBaseCfg;
    
    DDL_ZERO_STRUCT(stcBtBaseCfg);
    
    Sysctrl_SetPeripheralGate(SysctrlPeripheralBaseTim, TRUE); //Base Timer外设时钟使能
    
    stcBtBaseCfg.enWorkMode = BtWorkMode0;                  //定时器模式
    stcBtBaseCfg.enCT       = BtTimer;                      //定时器功能，计数时钟为内部PCLK
    stcBtBaseCfg.enPRS      = BtPCLKDiv32;                  //PCLK/32
    stcBtBaseCfg.enCntMode  = Bt32bitFreeMode;              //自动重载32位计数器/定时器
    stcBtBaseCfg.bEnTog     = FALSE;
    stcBtBaseCfg.bEnGate    = FALSE;
    stcBtBaseCfg.enGateP    = BtGatePositive;
    Bt_Mode0_Init(TIM0, &stcBtBaseCfg);                     //TIM0 的模式0功能初始化
}

/*******************************************************************************
 * TIM1中断服务函数
 ******************************************************************************/

void Tim1_IRQHandler(void)
{
    if(TRUE == Bt_GetIntFlag(TIM1, BtUevIrq))
    {
        Bt_ClearIntFlag(TIM1,BtUevIrq);

        Bt_M0_Stop(TIM1);

        uart_rx_busy_flag = FALSE;
        
        /* set uart recv evt */
        pt_uart_set_rx_evt();
        net_uart_set_evt();
    }
}

//Timer1配置初始化
void hw_timer1_cfg(void)
{
	uint16_t u16Period = 48000;
    uint16_t                  u16ArrValue;
    uint16_t                  u16CntValue;
    stc_bt_mode0_cfg_t     stcBtBaseCfg;
	
    //uart_packing_interval = ms
    uart_idle_timer_cnt = SystemCoreClock/16000*uart_packing_interval;
    uart_idle_timer_cnt = 0x10000 - uart_idle_timer_cnt;
	
    DDL_ZERO_STRUCT(stcBtBaseCfg);
    
    Sysctrl_SetPeripheralGate(SysctrlPeripheralBaseTim, TRUE); //Base Timer外设时钟使能
    
    stcBtBaseCfg.enWorkMode = BtWorkMode0;                  //定时器模式
    stcBtBaseCfg.enCT       = BtTimer;                      //定时器功能，计数时钟为内部PCLK
    stcBtBaseCfg.enPRS      = BtPCLKDiv16;                 //PCLK/256
    stcBtBaseCfg.enCntMode  = Bt16bitArrMode;               //自动重载16位计数器/定时器
    stcBtBaseCfg.bEnTog     = FALSE;
    stcBtBaseCfg.bEnGate    = FALSE;
    stcBtBaseCfg.enGateP    = BtGatePositive;
    Bt_Mode0_Init(TIM1, &stcBtBaseCfg);                     //TIM0 的模式0功能初始化
    
    //u16ArrValue = 0x10000 - u16Period;
    Bt_M0_ARRSet(TIM1, uart_idle_timer_cnt);                        //设置重载值(ARR = 0x10000 - 周期)
    
    //u16CntValue = 0x10000 - u16Period;
    Bt_M0_Cnt16Set(TIM1, uart_idle_timer_cnt);                      //设置计数初值
    
    Bt_ClearIntFlag(TIM1,BtUevIrq);                         //清中断标志   
    Bt_Mode0_EnableIrq(TIM1);                               //使能TIM0中断(模式0时只有一个中断)
    EnableNvic(TIM1_IRQn, IrqLevel3, TRUE);                 //TIM0中断使能
	
	//Bt_M0_Run(TIM1); 
}

void hw_timer1_restart(void)
{
    Bt_M0_Stop(TIM1);
	Bt_M0_Cnt16Set(TIM1, uart_idle_timer_cnt); 
    Bt_M0_Run(TIM1);  
}

void hw_rng_cfg(void)
{
    Sysctrl_SetPeripheralGate(SysctrlPeripheralRng, TRUE);
    Trng_Init();
}

void mcu_enter_lp(void)
{
    EnableNvic(UART0_IRQn, IrqLevel3, FALSE);

    __disable_irq();
    hw_lp_enter_gpio_cfg();
    __enable_irq();
    
    Lpm_GotoDeepSleep(FALSE);
}

void mcu_exit_lp(void)
{
    hw_pll_init();
    
    __disable_irq();
#ifdef DDL_UART_DMA_YES
    app_uart0_dma_cfg();
#endif

    hw_lp_exit_gpio_cfg();
    hw_uart_cfg();
    hw_spi_cfg();	

    __enable_irq();
}

#ifdef DDL_UART_DMA_YES
// DMA通道配置， ADC SQR触发DMA传输
void app_uart0_dma_cfg(void)
{
    stc_dma_cfg_t stcDmaCfg;
    
    DDL_ZERO_STRUCT(stcDmaCfg);   
    
    // 使能DMA时钟
    Sysctrl_SetPeripheralGate(SysctrlPeripheralDma, TRUE);   
    
    stcDmaCfg.enMode =  DmaMskBlock;                             //选择突发(Burst)传输    
    stcDmaCfg.u16BlockSize = 0x01u;                              //块传输个数
    stcDmaCfg.u16TransferCnt = 0x03u;                            //burst模式，一次触发传输数据大小为 3*3,
    stcDmaCfg.enTransferWidth = DmaMsk8Bit;                      //传输数据的宽度，此处选择字(8Bit)宽度     
    stcDmaCfg.enSrcAddrMode = DmaMskSrcAddrInc;                  //源地址固定
    stcDmaCfg.enDstAddrMode = DmaMskDstAddrFix;                  //目的地址自增
    stcDmaCfg.enDestAddrReloadCtl = DmaMskDstAddrReloadDisable;  //禁止重新加载传输目的地址
    stcDmaCfg.enSrcAddrReloadCtl = DmaMskSrcAddrReloadDisable;   //禁止重新加载传输源地址
    stcDmaCfg.enSrcBcTcReloadCtl = DmaMskBcTcReloadDisable;      //禁止重新加载BC/TC值
    stcDmaCfg.u32SrcAddress = (uint32_t)0x20000000;              //指定传输源地址
    stcDmaCfg.u32DstAddress = (uint32_t)&(M0P_UART0->SBUF);      //指定传输目的地址
    stcDmaCfg.enTransferMode = DmaMskOneTransfer;                //DMAC 在传输完成时清除 CONFA:ENS 位。允许Dma传输一次。
    stcDmaCfg.enRequestNum = DmaUart0TxTrig;                     //设置为ADCSQR触发
    stcDmaCfg.enPriority = DmaMskPriorityFix;                    //各通道固定优先级，CH0优先级 > CH1优先级
    
    Dma_InitChannel(DmaCh0,&stcDmaCfg);                          //初始化DMA通道0

    Dma_EnableChannelIrq(DmaCh0);
    Dma_EnableChannelErrIrq(DmaCh0);
    EnableNvic(DMAC_IRQn, IrqLevel3, TRUE);                      ///<系统中断使能
}

int hw_uart0_dma_send(u8 *buf, int len)
{
    uart_tx_busy_flag = TRUE;
    uart_dmac_tx_flag = FALSE;
    
    Dma_ClrStat(DmaCh0);
    
    Dma_SetTransferCnt(DmaCh0, len);
    Dma_SetSourceAddress(DmaCh0, (uint32_t)buf);
    Dma_Enable();
    Dma_EnableChannel(DmaCh0);
    Uart_EnableFunc(M0P_UART0, UartDmaTxFunc);
    
    while(!uart_dmac_tx_flag);
    while (TRUE != M0P_UART0->ISR_f.TC);
    
    Uart_DisableFunc(M0P_UART0, UartDmaTxFunc);
    
    uart_tx_busy_flag = FALSE;
    
    return len;
}

void Dmac_IRQHandler(void)
{
    uart_dmac_tx_flag = TRUE;
    Dma_ClrStat(DmaCh0);
}
#endif
/******************************************************************************
 * EOF (not truncated)
 ******************************************************************************/
 
